const express = require('express');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const cors = require('cors');

const app = express();
const PORT = 3001;
const DATA_DIR = path.join(__dirname, 'data');
const TOKEN = '2876ea85cb005fb5fa17c809a98174f2d5aae8b1f830110a5ead6211'; // token

if (!fs.existsSync(DATA_DIR)) {
  fs.mkdirSync(DATA_DIR);
}

app.use(cors());
app.use(express.json());

// 获取基金列表（直接读取stockList.json）
app.get('/api/funds', (req, res) => {
  const filePath = path.join(DATA_DIR, 'stockList.json');
  if (!fs.existsSync(filePath)) {
    return res.json([]);
  }
  const list = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
  res.json(list);
});

// 调用tushare API并保存结果
app.post('/api/call', async (req, res) => {
  const { code } = req.body;
  if (!code) return res.status(400).json({ msg: '缺少基金代码' });

  const postData = {
    api_name: 'fund_nav',
    token: TOKEN,
    params: {
      ts_code: code,
      trade_date: '',
      market: 'E',
      start_date: '20240512',
      end_date: '20250512',
    },
    fields: 'open,high,low,close,vol',
  };

  try {
    const response = await axios.post('http://api.tushare.pro', postData, {
      headers: { 'Content-Type': 'application/json' },
    });
    // 获取格式化时间（yyyy/MM/dd HH:mm:ss）
    function formatDate(date) {
      const pad = n => n.toString().padStart(2, '0');
      return date.getFullYear() + '/' + pad(date.getMonth() + 1) + '/' + pad(date.getDate()) + ' '
        + pad(date.getHours()) + ':' + pad(date.getMinutes()) + ':' + pad(date.getSeconds());
    }
    const now = formatDate(new Date());
    // 保存到本地JSON文件，并加上更新时间
    const filePath = path.join(DATA_DIR, 'stockList.json');
    let list = [];
    if (fs.existsSync(filePath)) {
      list = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    }
    // 更新对应基金的updateTime
    list = list.map(item => item.code === code ? { ...item, updateTime: now } : item);
    fs.writeFileSync(filePath, JSON.stringify(list, null, 2), 'utf-8');
    res.json({ msg: '数据已更新', data: response.data });
  } catch (err) {
    res.status(500).json({ msg: 'API调用失败', error: err.message });
  }
});

// 获取本地保存的基金数据
app.get('/api/data/:code', (req, res) => {
  const code = req.params.code;
  const filePath = path.join(DATA_DIR, `${code}.json`);
  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ msg: '无本地数据' });
  }
  const data = fs.readFileSync(filePath, 'utf-8');
  res.json(JSON.parse(data));
});

app.listen(PORT, () => {
  console.log(`Backend server running at http://localhost:${PORT}`);
}); 